﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LinqToSql
{
    class DAO
    {
        public static void Add(Customer cust)
        {
            NorthwindDataClassesDataContext context = new NorthwindDataClassesDataContext();
            using (context)
            {
                context.Customers.InsertOnSubmit(cust);
                context.SubmitChanges();
            }
        }

        public static void Delete(Customer cust)
        {
             NorthwindDataClassesDataContext context = new NorthwindDataClassesDataContext();
             using (context)
             {
                 Customer res =
                     (from c in context.Customers
                     where c.CustomerID == cust.CustomerID && c.CompanyName == cust.CompanyName
                     select c).FirstOrDefault();
                 context.Customers.DeleteOnSubmit(res);
                 context.SubmitChanges();
             }
        }

        public static void Modify(Customer oldCust, Customer newCust)
        {
            NorthwindDataClassesDataContext context = new NorthwindDataClassesDataContext();
            using (context)
            {
                if (context.Customers.Contains(oldCust))
                {
                    if (oldCust.CustomerID != newCust.CustomerID)
                    {
                        context.Customers.DeleteOnSubmit(oldCust);
                        context.Customers.InsertOnSubmit(newCust);
                    }
                    else
                    {
                        oldCust.Address = newCust.Address;
                        oldCust.City = newCust.City;
                        oldCust.CompanyName = newCust.CompanyName;
                        oldCust.ContactName = newCust.ContactName;
                        oldCust.ContactTitle = newCust.ContactTitle;
                        oldCust.Country = newCust.Country;
                        oldCust.CustomerCustomerDemos = newCust.CustomerCustomerDemos;
                        oldCust.Fax = newCust.Fax;
                        oldCust.Orders = newCust.Orders;
                        oldCust.Phone = newCust.Phone;
                        oldCust.PostalCode = newCust.PostalCode;
                        oldCust.Region = newCust.Region;
                    }
                }
                else
                {
                    context.Customers.InsertOnSubmit(newCust);
                }
                context.SubmitChanges();
            }
        }
    }
}
